package com.yuanfeng.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yuanfeng.business.dto.*;
import com.yuanfeng.business.entity.ShopClassEntity;
import com.yuanfeng.business.entity.ShopJoinBaseEntity;
import com.yuanfeng.business.entity.ShopJoinBaseTempEntity;
import com.yuanfeng.business.entity.ShopJoinPayEntity;
import com.yuanfeng.business.feign.BaseServiceClient;
import com.yuanfeng.business.feign.GoodsServiceClient;
import com.yuanfeng.business.feign.ThirdPartyServiceClient;
import com.yuanfeng.business.feign.UsermsServiceClient;
import com.yuanfeng.business.mapper.*;
import com.yuanfeng.business.service.ShopBaseService;
import com.yuanfeng.business.service.ShopJoinBaseService;
import com.yuanfeng.business.vo.*;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.constant.RedisConstants;
import com.yuanfeng.commoms.dto.userms.BusinessUserInfoDTO;
import com.yuanfeng.commoms.dto.userms.UserInfoDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.exception.GlobalExceptionEnum;
import com.yuanfeng.commoms.exception.UserDefinedException;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.vo.shop.ShopGoodsCatVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.GlobalTransactionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * (ShopJoinBase)
 *
 * @since 2023-05-19 15:35:47
 */
@Service
public class ShopJoinBaseServiceImpl extends ServiceImpl<ShopJoinBaseMapper, ShopJoinBaseEntity>
        implements ShopJoinBaseService {
    private static final Logger LOG = LoggerFactory.getLogger(ShopJoinBaseServiceImpl.class);

    @Autowired
    private ShopBaseService shopBaseService;

    @Autowired
    private ObjectMapper objectMapper;

    @Resource
    private ShopJoinBaseTempMapper shopJoinBaseTempMapper;

    @Autowired
    private BaseServiceClient baseServiceClient;

    @Resource
    private ShopJoinBaseMapper shopJoinBaseMapper;

    @Resource
    private ShopHelpMapper shopHelpMapper;

    @Resource
    private ShopClassMapper shopClassMapper;

    @Autowired
    private ShopJoinPayMapper shopJoinPayMapper;

    @Autowired
    private ShopClassBindMapper shopClassBindMapper;


    @Autowired
    private GoodsServiceClient goodsServiceClient;

    @Autowired
    private UsermsServiceClient usermsServiceClient;

    @Autowired
    private ThirdPartyServiceClient thirdPartyServiceClient;

    @Override
    public ResponseResult shopJoinAgree(Map<String, Object> param) {
        ResponseResult rr = new ResponseResult();
        ShopJoinInitResult data;
        String token = param.get("token").toString();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        String userId = userInfo.getUserId();
        param.put("userId", userId);
        data = this.baseMapper.queryShopJoinInfo(param);
        if (null != data) {
            data.setIsExist(1);
            Date currentDate = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String joinId = sdf.format(currentDate) + getRandom();
            data.setNewJoinId(joinId);
            rr.setCode(1);
            rr.setData(data);
            rr.setMessage("joinId获取成功");

        } else {
            data = new ShopJoinInitResult();
            try {
                String joinId = "";
                Date currentDate = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                joinId = sdf.format(currentDate) + getRandom();
                data.setNewJoinId(joinId);
                data.setIsExist(0);
                data.setShopType(null);
                rr.setCode(1);
                rr.setData(data);
                rr.setMessage("joinId生成成功");
            } catch (Exception e) {
                LOG.error(e.getMessage());
                rr.setCode(0);
                rr.setMessage("joinId生成失败");
            }
        }
        Integer count = this.baseMapper.queryShopBaseCount(param);
        if (null != count && count > 0) {
            data.setShopBaseExist(1);
            UserInfoDTO userInfoDTO = new UserInfoDTO();
            UserInfoVO userInfoTmp = this.baseMapper.getUserInfoByPhoneNumber(userId);
            userInfoDTO.setUser(userInfoTmp);
            if (null != token) {
                try {
                    RedisUtil.set(YFConfig.YF_USER_TOKEN_USER + token, objectMapper.writeValueAsString(userInfoDTO),
                            YFConfig.TOKEN_OUTTIME);
                    RedisUtil.set(YFConfig.YF_USER_TOKEN_USERID + token, userInfoTmp.getUserId(),
                            YFConfig.TOKEN_OUTTIME);
                } catch (Exception e) {
                    LOG.error(e.getMessage());
                }
            }
        } else {
            data.setShopBaseExist(0);
        }
        return rr;
    }
    // 创建一个随机数生成器
    public String getRandom() {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }
        return result;
    }


    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult insertShopJoinBase(Map<String, Object> param) throws TransactionException {
        try{
        ResponseResult rr = new ResponseResult();
        String token = param.get("token").toString();
        // 获取存储手机验证码
       String phoneCode = RedisUtil.get(RedisConstants.FKGOU_VERIFICODE_CLIENT_SESSION_ID + "_" + token);
       if(null == phoneCode){
           return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.VERIFICATION_CODE_OVERDUE.getMsg());
       }
        //查看登录状态
        String tokenRedis = YFConfig.YF_USER_TOKEN_USER + token;
        if (!RedisUtil.exists(tokenRedis)) {
            throw new UserDefinedException(GlobalExceptionEnum.NO_FORBIDDEN, GlobalExceptionEnum.NO_FORBIDDEN.getErrorMsg());
        }
        UserInfoVO userInfoEntity = ParseTokenUtils.getUserInfoByTokenNoIsExist(token);
        //UserInfoEntity userInfoEntity = JSON.parseObject(RedisUtil.get(tokenRedis), UserInfoEntity.class);
        String userId = userInfoEntity.getUserId();
        param.put("userId",userId);
        //根据userid查待审核的店铺
        Integer count = this.baseMapper.queryAuditingShopCount(param);
        if(count > 0){
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.OPERATE_ERROR.getMsg());
        }
        String validateCode = "";
        if(null != param.get("validateCode")) {
            validateCode = param.get("validateCode").toString();
        }
        if(validateCode.equals(phoneCode)) {
            //短信校验后就删除
            RedisUtil.remove(RedisConstants.FKGOU_VERIFICODE_CLIENT_SESSION_ID+"_" + token);
            //插入店铺信息
            this.baseMapper.insertShopJoinBase(param);
            shopJoinBaseTempMapper.insertShopJoinBaseTemp(param);
            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
        }else{
            return ResponseResult.fail(BizCodeEnume.INCORRECT_VERIFICATION_CODE);
        }
        }catch (Exception e){
            // 回滚
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult updateShopJoinBase(Map<String, Object> param) {
        ResponseResult rr = new ResponseResult();
        String token = param.get("token").toString();
        // 获取存储手机验证码
        String phoneCode = RedisUtil.get(RedisConstants.FKGOU_VERIFICODE_CLIENT_SESSION_ID+"_" + token);
        if(null == phoneCode){
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.VERIFICATION_CODE_OVERDUE.getMsg());
        }
        //查看登录状态
        String tokenRedis = RedisConstants.FKGOU_USER_TOKEN_USER + token;
        if (!RedisUtil.exists(tokenRedis)) {
            throw new UserDefinedException(GlobalExceptionEnum.NO_FORBIDDEN, GlobalExceptionEnum.NO_FORBIDDEN.getErrorMsg());
        }
        UserInfoVO userInfoEntity = ParseTokenUtils.getUserInfoByToken(token);
        String userId = userInfoEntity.getUserId();
        param.put("userId",userId);

        String validateCode = "";
        if(null != param.get("validateCode")) {
            validateCode = param.get("validateCode").toString();
        }
        if(validateCode.equals(phoneCode)) {
            try {
                this.baseMapper.updateShopJoinBase(param);
                rr.setCode(CommonStatusEnum.SUCCESS.getCode());
                rr.setMessage(BizCodeEnume.OPERATION_SUCCESSFUL.getMsg());
            } catch (Exception e) {
                rr.setCode(CommonStatusEnum.FAIL.getCode());
                rr.setMessage(BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
                LOG.error(e.getMessage());
            }
        }else{
            rr.setCode(CommonStatusEnum.FAIL.getCode());
            rr.setMessage(BizCodeEnume.INCORRECT_VERIFICATION_CODE.getMsg());
        }
        return rr;
    }

    @Override
    public ResponseResult queryShopJoinBase(Map<String, Object> param) {
        ResponseResult rr = new ResponseResult();
        String token = param.get("token").toString();
        //查看登录状态
        String tokenRedis = RedisConstants.FKGOU_USER_TOKEN_USER + token;
        if (!RedisUtil.exists(tokenRedis)) {
            throw new UserDefinedException(GlobalExceptionEnum.NO_FORBIDDEN, GlobalExceptionEnum.NO_FORBIDDEN.getErrorMsg());
        }
        UserInfoVO userInfoEntity = ParseTokenUtils.getUserInfoByTokenNoIsExist(token);
//        UserInfoEntity userInfoEntity = JSON.parseObject(RedisUtil.get(tokenRedis), UserInfoEntity.class);
        String userId = userInfoEntity.getUserId();
        param.put("userId",userId);
        ShopJoinInfoVO data = this.baseMapper.queryShopJoinBase(param);
        if (data != null) {
            String blLocation = getAddress(data.getBlProvince() + "", data.getBlCity() + "", data.getBlArea() + "");
            data.setBlLocation(blLocation);
            String shopLocation = getAddress(data.getShopProvince() + "", data.getShopCity() + "", data.getShopArea() + "");
            data.setShopLocation(shopLocation);
            data.setUserId(userInfoEntity.getUserId());
        }
        rr.setCode(CommonStatusEnum.SUCCESS.getCode());
        rr.setData(data);
        rr.setMessage(BizCodeEnume.OPERATION_SUCCESSFUL.getMsg());
        return rr;
    }

    private String getAddress(String provinceId, String cityId, String districtId) {
        if ((provinceId == null || provinceId.equals("")|| provinceId.equals("null"))
                && (cityId == null || cityId.equals("") || cityId.equals("null"))
                && (districtId == null || districtId.equals("") || districtId.equals("null"))) {
            return "";
        }
        String provinceName = baseServiceClient.queryProvinceport(provinceId);
        String cityName = baseServiceClient.queryProvinceport(cityId);
        String districtName = baseServiceClient.queryProvinceport(districtId);
        return provinceName + cityName + districtName;
    }

    @Override
    public ResponseResult queryPayEvidence(Map<String, Object> param) {
        ResponseResult rr = new ResponseResult();
        String token = param.get("token").toString();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        String userId = userInfo.getUserId().toString();
        param.put("userId", userId);
        try {
            ShopPayInitInfoVO data = shopJoinBaseMapper.queryShopPayInfo(param);
            rr.setCode(CommonStatusEnum.SUCCESS.getCode());
            rr.setData(data);
            rr.setMessage(BizCodeEnume.OPERATION_SUCCESSFUL.getMsg());
        } catch (Exception e) {
            rr.setCode(CommonStatusEnum.FAIL.getCode());
            rr.setMessage("出现异常");
            LOG.error(e.getMessage());
        }
        return rr;
    }

    @Override
    public ResponseResult queryShopHelp(ShopHelpQueryDTO param) {
        String helpInfo = shopHelpMapper.selectByShopHelpId(param.getShopHelpId());
        return ResponseResult.success(helpInfo);
    }

    @Override
    public ResponseResult checkCompanyName(Map<String, Object> param) {
        ResponseResult rr = new ResponseResult();
        Integer isExist = 0;
        try {
            isExist = shopJoinBaseMapper.checkCompanyName(param);
            rr.setCode(CommonStatusEnum.SUCCESS.getCode());
            rr.setData(isExist);
            rr.setMessage(BizCodeEnume.OPERATION_SUCCESSFUL.getMsg());
        }catch (Exception e){
            LOG.error(e.getMessage());
            rr.setCode(CommonStatusEnum.FAIL.getCode());
            rr.setMessage(BizCodeEnume.MYSQL_EXCEPTION.getMsg());
        }
        return rr;
    }

    @Override
    public ResponseResult checkPhoneNumber(Map<String, Object> param) {
        ResponseResult rr = new ResponseResult();
        Integer isExist = 0;
        try {
            isExist = shopJoinBaseMapper.checkPhoneNumber(param);
            rr.setCode(CommonStatusEnum.SUCCESS.getCode());
            rr.setData(isExist);
            rr.setMessage(CommonStatusEnum.SUCCESS.getValue());
        }catch (Exception e){
            LOG.error(e.getMessage());
            rr.setCode(CommonStatusEnum.FAIL.getCode());
            rr.setMessage(BizCodeEnume.MYSQL_EXCEPTION.getMsg());
        }

        return rr;
    }

    @Override
    public ResponseResult queryShopJoinDetailForPlatform(Map<String, Object> param) {
        ShopJoinInfoDetailForPlatformVO data = new ShopJoinInfoDetailForPlatformVO();
        data = this.baseMapper.queryShopJoinDetailForPlatformEntity(param);
        String completeBankAddress = "";
        completeBankAddress = getAddress(data.getBankProvince()+"",data.getBankCity()+"",data.getBankArea()+"");
        if(data.getBankAddress() == null){
            data.setBankAddress("");
        }
        completeBankAddress = completeBankAddress + data.getBankAddress();
        data.setCompleteBankAddress(completeBankAddress);
        String completeAddress = "";
        String completeBlAddress = "";
        completeAddress = getAddress(data.getShopProvince()+"",data.getShopCity()+"",data.getShopArea()+"");
        if(data.getShopAddress() == null){
            data.setShopAddress("");
        }
        completeAddress = completeAddress + data.getShopAddress();
        data.setCompleteShopAddress(completeAddress);
        completeBlAddress = getAddress(data.getBlProvince()+"",data.getBlCity()+"",data.getBlArea()+"");
        if(data.getBlAddress() == null){
            data.setBlAddress("");
        }
        completeBlAddress = completeBlAddress + data.getBlAddress();
        data.setCompleteBlAddress(completeBlAddress);
        if(null != data.getShopClass()){
            BigDecimal shopPay = shopClassMapper.selectOne(new LambdaQueryWrapper<ShopClassEntity>()
                                .eq(ShopClassEntity::getShopClassId,data.getShopClass())).getShopPay();
            data.setShopPay(shopPay);
        }
        Integer shopType = data.getShopType();
        param.put("userId",data.getUserId());
        if(null != shopType && 0 != shopType){
            //若为非个人入驻 需要查验是否实名
            Map<String, Object> shopPersonInfo = this.baseMapper.queryShopPersonInfo(param);
            if(null != shopPersonInfo) {
                data.setIdType(Integer.valueOf(shopPersonInfo.get("idType").toString()));
                data.setTrueName(shopPersonInfo.get("trueName").toString());
                data.setIdNo(shopPersonInfo.get("idNo").toString());
                data.setIdPicOne(shopPersonInfo.get("idPicOne").toString());
                data.setIdPicTwo(shopPersonInfo.get("idPicTwo").toString());
            }
        }

        return ResponseResult.success(data);
    }

    @Override
    public ResponseResult queryShopJoinBaseBankForSeller(Map<String, Object> param) {
        String token = param.get("token").toString();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        String userId = userInfo.getUserId();
        param.put("userId",userId);
        ShopJoinInfoBaseBankForSellerDTO data = this.baseMapper.queryShopJoinBaseBankForSeller(param);
        String completeBankAddress = getAddress(data.getBankProvince()+"",data.getBankCity()+"",data.getBankArea()+"");
        if(data.getBankAddress() == null){
            data.setBankAddress("");
        }
        completeBankAddress = completeBankAddress + data.getBankAddress();
        if (completeBankAddress.equals("nullnullnull")) {
            completeBankAddress = "";
        }
        data.setCompleteBankAddress(completeBankAddress);
        return ResponseResult.success(data);
    }

    @Override
    public ResponseResult queryShopJoinBaseForSeller(Map<String, Object> param) {
        String token = param.get("token").toString();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        String userId = userInfo.getUserId();
        param.put("userId",userId);
        ShopJoinInfoBaseForSellerDTO data = this.baseMapper.queryShopJoinBaseForSeller(param);
        Integer shopType = data.getShopType();
        String completeAddress = getAddress(data.getShopProvince()+"",data.getShopCity()+"",data.getShopArea()+"");
        if(data.getShopAddress() == null){
            data.setShopAddress("");
        }
        completeAddress = completeAddress + data.getShopAddress();
        data.setCompleteShopAddress(completeAddress);
        if(null != shopType && 0 != shopType){
            //若为非个人入驻 需要查验是否实名
            ShopPersonInfoDTO shopPersonInfo = this.baseMapper.queryShopPersonInfo2(param);
            if(null != shopPersonInfo) {
                data.setValidateLongTerm(shopPersonInfo.getValidateLongTerm());
                data.setIdType(shopPersonInfo.getIdType());
                data.setTrueName(shopPersonInfo.getTrueName());
                data.setIdNo(shopPersonInfo.getIdNo());
                data.setIdPicOne(shopPersonInfo.getIdPicOne());
                data.setIdPicTwo(shopPersonInfo.getIdPicTwo());
                data.setValidateStartTime(shopPersonInfo.getValidateStartTime());
                data.setValidateEndTime(shopPersonInfo.getValidateEndTime());
            }
        }

        int status = (null != data.getIdPicOne() && null != data.getIdPicTwo()
                && !"".equals(data.getIdPicOne()) && !"".equals(data.getIdPicTwo())) ? 1 : 0;
        data.setIsCertified(status);
        return ResponseResult.success(data);
    }

    @Override
    public ResponseResult queryShopJoinBaseQualiForSeller(Map<String, Object> param) {
        String token = param.get("token").toString();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (null == userInfo.getShopId()) {
            return ResponseResult.fail(10086, "没有权限");
        }
        String userId = userInfo.getUserId();
        param.put("userId", userId);
        ShopJoinInfoBaseQualiForSellerVO data = this.baseMapper.queryShopJoinBaseQualiForSeller(param);
        String completeAddress = "";
        String completeBlAddress = "";
        completeAddress = getAddress(data.getShopProvince() + "", data.getShopCity() + "", data.getShopArea() + "");
        if (data.getShopAddress() == null) {
            data.setShopAddress("");
        }
        data.setShopLocation(completeAddress);
        completeAddress = completeAddress + data.getShopAddress();
        data.setCompleteShopAddress(completeAddress);
        completeBlAddress = getAddress(data.getBlProvince()+"",data.getBlCity()+"",data.getBlArea()+"");
        if(data.getBlAddress() == null){
            data.setBlAddress("");
        }
        data.setBlLocation(completeBlAddress);
        completeBlAddress = completeBlAddress + data.getBlAddress();
        data.setCompleteBlAddress(completeBlAddress);
        return ResponseResult.success(data);
    }

    @Override
    public ResponseResult updateShopJoinBaseForSeller(Map<String, Object> param) {
        try {
            this.baseMapper.updateShopJoinBaseForSeller(param);
            return ResponseResult.success();
        } catch (Exception e) {
            LOG.error(e.getMessage());
            return ResponseResult.fail(2,"出现异常");
        }
    }

    @Override
    public ResponseResult updateShopJoinBankInfoForSeller(Map<String, Object> param) {
        try {
            this.baseMapper.updateShopJoinBankInfoForSeller(param);
            return ResponseResult.success();
        } catch (Exception e) {
            LOG.error(e.getMessage());
            return ResponseResult.fail(2,"出现异常");
        }
    }

    @Override
    public ResponseResult shopAgree(Map<String, Object> param) {
        ResponseResult rr = new ResponseResult();
        ShopJoinInitResult data;
        String token = param.get("token").toString();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        String userId = userInfo.getUserId();
        param.put("userId",userId);
        data =  this.baseMapper.queryShopJoinInfo(param);
        if(null != data){
            data.setIsExist(1);
            Date currentDate = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String joinId = sdf.format(currentDate) + getRandom();
            data.setNewJoinId(joinId);
            rr.setCode(1);
            rr.setData(data);
            rr.setMessage("joinId获取成功");

        }else {
            data = new ShopJoinInitResult();
            try {
                String joinId = "";
                Date currentDate = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                joinId = sdf.format(currentDate) + getRandom();
                data.setNewJoinId(joinId);
                data.setIsExist(0);
                data.setShopType(null);
                rr.setCode(1);
                rr.setData(data);
                rr.setMessage("joinId生成成功");
            } catch (Exception e) {
                LOG.error(e.getMessage());
                rr.setCode(2);
                rr.setMessage("joinId生成失败");
            }
        }
        int isSubAccount = 0;
        if(userInfo.getShopId() != null){
            List<UserSellerBaseDTO> userSellerBases = this.baseMapper.getSubAccount(userInfo.getShopId());
            if (userSellerBases != null && !userSellerBases.isEmpty()) {
                for (UserSellerBaseDTO userSellerBase : userSellerBases) {
                    if (userSellerBase.getUserId().equals(userId)) {
                        isSubAccount = 1;
                    }
                }
            }
        }
        Integer count = this.baseMapper.queryShopBaseCount(param);
        if(null != count && count>0) {
            data.setShopBaseExist(1);
            UserInfoVO userInfoTmp = this.baseMapper.getUserInfoByPhoneNumber(userId);
            if (null != token) {
                Integer status = this.baseMapper.queryShopStatus(userInfo.getUserId());
                if (status > 0) {
                    userInfoTmp.setIsShop(1);
                } else {
                    userInfoTmp.setIsShop(2);
                }
                BusinessUserInfoDTO detail = this.baseMapper.queryInfo(param);
                if (detail == null) {
                    String createUser = this.baseMapper.getPrimaryAccountId(userId);
                    param.put("userId", createUser);
                    //detail = this.baseMapper.queryInfo(param);
                }
                userInfoTmp.setBusinessDetail(detail);
                UserInfoDTO userInfoDTO = new UserInfoDTO();
                userInfoDTO.setUser(userInfoTmp);
                try {
                    RedisUtil.set(YFConfig.YF_USER_TOKEN_USER + token, objectMapper.writeValueAsString(userInfoDTO),
                            YFConfig.TOKEN_OUTTIME);
                    RedisUtil.set(YFConfig.YF_USER_TOKEN_USERID + token, userInfoTmp.getUserId(),
                            YFConfig.TOKEN_OUTTIME);
                } catch (Exception e) {
                    LOG.error(e.getMessage());
                }
            }
        }else if(isSubAccount == 1){
            data.setShopBaseExist(2);
        }else{
            data.setShopBaseExist(0);
        }
        return rr;
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult auditShopJoinBase(Map<String, Object> param) throws TransactionException {
        Integer auditStatus = (Integer) param.get("auditStatus");
        try {
            ShopJoinBaseEntity shopJoinBase = ParseMapUtils.parseMap2Object(param, ShopJoinBaseEntity.class);
            this.update(null, new LambdaUpdateWrapper<ShopJoinBaseEntity>()
                                    .set(ShopJoinBaseEntity::getAuditStatus,auditStatus)
                                    .set(ShopJoinBaseEntity::getLastUpdateTime,new Date())
                                    .set(param.containsKey("auditComment"),ShopJoinBaseEntity::getAuditComment,param.containsKey("auditComment")?param.get("auditComment").toString():null)
                                   .eq(ShopJoinBaseEntity::getJoinId, param.get("joinId").toString()));

            shopJoinBaseTempMapper.updateShopJoinBaseTempAuditStatus(String.valueOf(param.get("joinId")),auditStatus);
            ShopJoinBaseEntity entity=this.baseMapper.selectById(param.get("joinId").toString());
            //查询用户手机号
            String phone = this.baseMapper.selectuserphone(entity.getUserId());
            //发送手机短信通知
            HashMap map = new HashMap();
            map.put("userMobile",phone);
            map.put("smstype",3);
            if (CommonType.isApproved.APPROVED.getCode().equals(auditStatus)) {
                //查找店铺入驻信息
                ShopJoinBaseTempEntity data = shopJoinBaseTempMapper.selectOne(new LambdaQueryWrapper<ShopJoinBaseTempEntity>()
                                            .eq(ShopJoinBaseTempEntity::getJoinId,param.get("joinId").toString()));
                if(null==data){
                    shopJoinBaseTempMapper.auditShopInsertShopJoinBaseTemp(entity);
                }

                param.put("contactName", entity.getContactName());
                param.put("contactPhone", entity.getContactPhone());
                param.put("shopName", entity.getShopName());
                param.put("shopType", entity.getShopType());
                param.put("shopClass", entity.getShopClass());
                param.put("userId", entity.getUserId());
                if (null != entity.getShopClass()) {
                    // 查找店铺租金
                    BigDecimal shopPay = shopClassMapper.selectOne(new LambdaQueryWrapper<ShopClassEntity>()
                                                       .eq(ShopClassEntity::getShopClassId,entity.getShopClass())).getShopPay();
                    entity.setShopPay(shopPay);
                    param.put("shopPay", entity.getShopPay());
                }
                //查询是否有上传过支付信息
                ShopJoinPayEntity joinPay = shopJoinPayMapper.selectOne(new LambdaQueryWrapper<ShopJoinPayEntity>()
                        .eq(ShopJoinPayEntity::getUserId, entity.getUserId())
                        .eq(ShopJoinPayEntity::getShopType,(Integer) param.get("shopType")));
                if (joinPay !=null) {
                    Integer payId = joinPay.getPayId();
                    shopJoinPayMapper.update(null,new LambdaUpdateWrapper<ShopJoinPayEntity>()
                                    .set(ShopJoinPayEntity::getShopType,entity.getShopType())
                                    .eq(ShopJoinPayEntity::getPayId,payId));

                   // shopJoinPayMapper.updateShopPayShopType(payId, entity.getShopType());
//                    //更改商家店铺类型
//                    shopBaseService.update(new LambdaUpdateWrapper<ShopBaseEntity>()
//                            .set(ShopBaseEntity::getShopBusiness, CommonType.ShopBusiness.BUSINESS.getCode())
//                            .eq(ShopBaseEntity::getUserId, param.get("userId")));
//                    //更改店铺入驻信息店铺类型
//                    this.update(new LambdaUpdateWrapper<ShopJoinBaseEntity>()
//                            .set(ShopJoinBaseEntity::getShopType, CommonType.ShopType.COMMON_SHOP.getCode())
//                            .set(ShopJoinBaseEntity::getAuditComment, param.get("auditComment"))
//                            .eq(ShopJoinBaseEntity::getUserId, param.get("userId")));
//                    //更改店铺入驻支付店铺类型
//                    shopJoinPayMapper.update(null,new LambdaUpdateWrapper<ShopJoinPayEntity>()
//                            .set(ShopJoinPayEntity::getShopType, CommonType.ShopType.COMMON_SHOP.getCode())
//                            .eq(ShopJoinPayEntity::getUserId, param.get("userId")));
                } else {
                    //新增店铺入驻支付信息
                    param.put("auditStatus",CommonType.commonStatus.NO.getCode());
                    shopJoinPayMapper.insertShopJoinPay(param);
                }
                entity.setAuditStatus(auditStatus);
                //审核通过将临时表数据同步到原表
                this.baseMapper.updateById(entity);
                //发送短信参数
                map.put("result1","已通过");
                map.put("result2","您还查最后一步啦，请登录网站查询结果~");
            }else{
                //发送短信参数
                map.put("result1","未通过");
                map.put("result2","由于" + param.get("auditComment") + "原因审核失败");
            }
            //发送短信
            thirdPartyServiceClient.storeQualification(map);
            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
        } catch (Exception e) {
            e.printStackTrace();
            LOG.error(e.getMessage());
            // 回滚
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult queryShopJoinBaseDetailForPlatform(Map<String, Object> param) {
        //  查找店铺入驻详情
        ShopJoinInfoDetailForPlatformVO data = this.getBaseMapper().queryShopJoinBaseDetailForPlatform(param);
        // 店铺经营地址
        String shopLocation = baseServiceClient.getAddressString(data.getShopProvince(), data.getShopCity(), data.getShopArea()).getData().toString();
        data.setShopLocation(shopLocation);
        // 营业执照地址
        if (data.getBlProvince() != 0 &&  data.getBlCity() != 0 && data.getBlArea() != 0 ) {
            String blLocation = baseServiceClient.getAddressString(data.getBlProvince(), data.getBlCity(), data.getBlArea()).getData().toString();
            data.setBlLocation(blLocation);
        }
        if (null != data.getShopClass()) {
            // 查找店铺租金
            BigDecimal shopPay = shopClassMapper.selectOne(new LambdaQueryWrapper<ShopClassEntity>()
                    .eq(ShopClassEntity::getShopClassId,data.getShopClass())).getShopPay();
            data.setShopPay(shopPay);
        }
        // 查询店铺绑定分类
        List<ClassBindVO> classBindList = shopClassBindMapper.selectByShopIdOrJoinIdList(param);
        // 查询所有分类
        List<ShopGoodsCatVO> rootMenus =  shopClassBindMapper.selectAllCat3();
        for (ClassBindVO classBind : classBindList) {
            List<String> catNames = MenListUtils.getMenuList4(rootMenus, classBind.getProductClassId());
            classBind.setCatNames(catNames);
        }
        data.setShopSellClassEntityList(classBindList);
        return ResponseResult.success(data);
    }

    @Override
    public ResponseResult queryShopJoinBaseForPlatform(Map<String, Object> param) {
        //设置分页数据
        Page<ShopJoinInfoForPlatformVO> page = new Page<>((Integer) param.get("page"), (Integer) param.get("limit"));
        //查询待审核入驻店铺列表
        IPage<ShopJoinInfoForPlatformVO> dataList = this.baseMapper.selectShopJoinBaseForPlatform(page, param);
        //待审核入驻店铺总数
        for (ShopJoinInfoForPlatformVO entity : dataList.getRecords()) {
            //经营地址
            String shopLocation = baseServiceClient.getAddressString(entity.getShopProvince(), entity.getShopCity(), entity.getShopArea()).getData().toString();
            entity.setShopLocation(shopLocation);
            UserInfoVO vo = new UserInfoVO();
            vo.setUserId(entity.getUserId());
            ResponseResult uiStr = usermsServiceClient.queryUserInfo(vo);
            UserInfoVO ui = JSON.parseObject(JSON.toJSONString(uiStr.getData()), UserInfoVO.class);
            entity.setUserName(ui.getUserNickname() != null ? ui.getUserNickname() : ui.getUserName());
        }
        return ResponseResult.success(PageUtils.getPage(dataList));
    }


}

